package com.medical.logback.service;

import com.medical.logback.entity.Student;
import com.medical.logback.entity.User;
import com.medical.logback.exception.BizException;
import com.medical.logback.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:gzf
 * @Date : 2022/06/23
 */
@Slf4j
@Service
public class TestServiceImpl {

    public void testOne() {
        log.info("纯测试打印");
    }

    public String testT(String name) {
        return name;
    }

    public Student postTest(Student student) {
        return student;
    }

    /**
     * 出现异常不影响主流程运行
     */
    public void exceptionTest() {
        int i = 0;
        int j = 1 / i;
        log.info("分母为0");
    }

    /**
     * 出现异常需要回滚
     */
    public void exceptionRollBack() {
        List list = null;
        Object o = list.get(0);
        log.info("不再执行");
    }

    /**
     * 抛出指定异常
     */
    public void BizException() {
        //模拟查询数据库用户
        User user = new User(1L, "张三", "普通用户");

        if ("普通用户".equals(user.getRoleName())) {
            log.warn("userName:{} 无权限,当前接口需要超级管理员才可以访问", user.getName());
            throw new BizException(ResultCode.NO_PERMISSION);
        }
    }

    /**
     * 耗时功能示例
     */
    public void requestHttpUrl() {
        User user = new User(1L, "张三", "普通用户");
        String url = "https://www.baidu.com";
        long start = System.currentTimeMillis();
        String resp = null;
        try {
            log.info("requestHttpUrl请求外部URL:{}, param: {},", url, user.toString());
            //模拟请求
            Thread.sleep(1000);
            //请求结束 resp解析
            resp = "test";
        } catch (InterruptedException e) {
            log.error("请求外部URL:{}, param: {} , 异常.耗时:{}ms", url, user.toString(), (System.currentTimeMillis() - start));
            throw new BizException(ResultCode.ERROR);
        }
        log.info("请求外部URL:{}, reseponse: {} ,耗时:{}ms ", url, resp, (System.currentTimeMillis() - start));

    }
}
